﻿@model ItemControllerModel.Create
<div class="ui-box  ui-box-alpha">
    <div class="ui-box-head">
        <div class="ui-box-head-border">
            <div class="ui-box-head-title">
                发产商品
            </div>
        </div>
    </div>
    <div class="ui-box-container-noborder">
        <div class="ui-box-content">
            dd
        </div>
    </div>
    <div id="category-info" class="ui-box-container-noborder">
        <div class="ui-box-container-head">
            商品类别
        </div>
        <div class="ui-box-content">
            <div id="category-container" class="row">
                <div id="category-0" class="col-md-3">
                    <div class="category-tree">
                        <div class="panel-group" id="accordion">
                            @foreach (var o in Model.Groups)
                            {
                                var tmp = o;
                                <div class="panel panel-default">
                                    <div class="panel-heading">
                                        <h4 class="panel-title">
                                            <a class="accordion-toggle" data-toggle="collapse" href="#collapse-@o.Id">
                                                @o.Name
                                            </a>
                                        </h4>
                                    </div>
                                    <div id="collapse-@o.Id" class="panel-collapse collapse @(o.Expand ? "in" : string.Empty)">
                                        <div class="panel-body">
                                            <ul class="list-unstyled">
                                                @foreach (var c in Model.Categories.Where(i => i.Id.IsIn(tmp.Categories)))
                                                {
                                                    if (c.IsParent)
                                                    {
                                                        <li class="category-tree-item" onclick="getChildren(this,0,@(c.Id),'@(c.Id)')">
                                                            @c.Name
                                                        </li>
                                                    }
                                                    else
                                                    {
                                                        <li class="category-tree-item" onclick="publishItem(@(c.Id),'@(c.Id)')">
                                                            @c.Name
                                                        </li>
                                                    }

                                                }
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            }
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="item-info" class="ui-box-container-noborder">
        <form id='form-upload' action='/item/upload/' method="POST" target='frame-upload'
              enctype='multipart/form-data' style="display: none;">
            <iframe id='frame-upload' style='display: none' name='frame-upload'></iframe>
        </form>
        <div class="ui-box-container-head">
            商品信息 <a onclick="$('#category-info').toggle();" href="javascript:void(0);">显示分类</a>
        </div>
        <div id="item-container">
        </div>
    </div>
</div>
@section css{
    <style type="text/css">
        #category-container li {
        }

        .category-tree {
            height: 400px;
            overflow: auto;
        }

        .category-tree-item {
            line-height: 24px;
            cursor: pointer;
        }

        .category-tree-item-selected {
            background-color: #DFF1FB;
            border: 1px solid #9CD7FC;
        }

        dl dt {
            font-weight: normal;
        }

            dl dt span {
                margin-left: 5px;
            }

        .list-inline > li:first-child {
            padding-left: 5px;
        }

        .pic-box {
            border: 1px solid #dedede;
            color: #808080;
            display: block;
        }

        .pic-box-current {
            border-color: #ffc097;
        }

        .sku-color, .sku-map {
            padding: 10px 0px;
        }

        .ui-msg-alert {
            color: red;
            padding-left: 5px;
        }

        .prop-wrap {
            background-color: #f8f8f8;
            border: 1px solid #ececec;
        }

        .prop-wrap-blue {
            border: 1px solid #d5e4fa;
            background-color: #f5f9ff;
        }

        .prop-container {
            padding: 5px 10px;
        }

        .prop-item {
            margin-top: 5px;
            margin-bottom: 10px;
        }

        .a-input-file {
            display: block;
            position: relative;
            font-size: 12px;
            font-weight: normal;
            width: 100px;
            height: 26px;
            overflow: hidden;
            border: 1px solid #EBEBEB;
            background: none repeat scroll 0 0 #F3F3F3;
            color: #999999;
            cursor: pointer;
            text-align: center;
        }

            .a-input-file .input-file {
                display: block;
                position: absolute;
                top: 0;
                left: 0;
                width: 100px;
                height: 26px;
                font-size: 100px;
                opacity: 0;
                filter: alpha(opacity=0);
            }

        .image-preview {
            border: 1px solid #dedede;
            padding: 2px;
        }

            .image-preview img {
                width: 100px;
                height: 100px;
            }
    </style>
}
@section js{
    <script src="http://tinymce.cachefly.net/4.0/tinymce.min.js"></script>
    <script type="text/template" id="categories-template">
        <div id="<%=model.Id%>" class="col-md-3">
            <div class="category-tree">
                <ul class="list-unstyled">
                    <%var index= model.Index;%>
                    <% _.each(model.Data,function(o) { %>
                    <%if(o.IsParent){%>
                    <li class="category-tree-item" onclick="getChildren(this,<%=index %>,<%= o.Id %>,'<%= model.HierarchyId %>/<%= o.Id %>')"><%= o.Name %></li>
                    <%}else{%>
                    <li class="category-tree-item" onclick="publishItem(<%= o.Id %>,'<%= model.HierarchyId %>/<%= o.Id %>');"><%= o.Name %></li>
                    <%}}); %>
                </ul>
            </div>
        </div>
    </script>
    <script type="text/template" id="sku-template">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <%_.each(Names,function(o){%>
                    <th>
                        <%=o%>
                    </th>
                    <%});%>
                    <th>
                        价 格<span style="color:red;">*</span>
                    </th>
                    <th>
                        数 量<span style="color:red;">*</span>
                    </th>
                </tr>
            </thead>
            <tbody>
                <%for(var i=0;i
                <row;i++){ var id="prop-" ; %>
                    <tr>
                        <%if(Keys.length>1){ for(var j=0;j
                        <keys.length;j++){%>
                            <%if(j<keys.length-1 && i%keys[keys.length-1].length= =0 &&keys[keys.length-1].length>
                                0){%>
                                <%
                                var row=1;
                                var last=0;
                                for(var r=j+1;r<=Keys.length-1;r++){
                                if(r==Keys.length-1){
                                var len=Keys[r].length;

                                last=len;

                                }else{
                                var len=Keys[r].length;
                                if(len>1){
                                row*=len;
                                }
                                else{
                                row=0;
                                row+=len;
                                }
                                }
                                }
                                %>
                                <%if(i%(row*last)==0){%>
                                <td
                                    <%=(row*last)>1?"rowspan="+(row*last):""%>>
                                    <%if(j==0){%>

                                    <%=Sku.GetValue(Keys[j][(i/(row*last))]) %>

                                    <%}else{%>

                                    <%=Sku.GetValue(Keys[j][(i/(row*last))%Keys[j].length])%>
                                </td>
                                <%}%>
                                <%}%>
                                <%}else if(j=Keys.length-1){%>
                                <td>
                                    <%id+=Keys[j][i%Keys[j].length]+"-";%>

                                    <%=Sku.GetValue(Keys[j][i%Keys[j].length])%>
                                </td>
                                <%}else{%>
                                id+=Keys[j][(i/(row*last))]+"-";

                                <%}%>


                                <%}%>

                                <%}else{%>
                                <td>
                                    <%id+=Keys[0][i];%>
                                    <%=Sku.GetValue(Keys[0][i])%>
                                </td>
                                <%}%>

                                <td>
                                    <%=id%>
                                </td>
                                <td></td>
                    </tr>
                    <%}%>
            </tbody>

        </table>
    </script>
    <script type="text/template" id="item-template">
        <%
        var keyProps=_.sortBy(_.where(model.Props,{IsKeyProp:true,ParentPid:0}),"Priority");
        var saleProps=_.sortBy(_.where(model.Props,{IsSaleProp:true}),"Priority");
        var otherProps=_.sortBy(_.where(model.Props,{IsKeyProp:false,IsSaleProp:false,ParentPid:0}),"Priority");
        Sku.SaleProps=saleProps;
        Sku.PropValues=model.PropValues;
        %>
        <form action="/item/create" method="post" onsubmit="return checkForm(this);">
            <div class="row">
                <div class="col-md-3">
                    <div style="padding: 10px;margin-bottom:20px; border-right: 1px solid #CCCCCC;border-bottom: 1px solid #CCCCCC;">
                        <p>
                            产品信息
                        </p>
                        <dl>
                            <%_.each(otherProps,function(o){%>
                            <dt>
                                <%=o.Name%><%if(o.Required==true){%><span style="color: red;">*</span><%}%>
                            </dt>
                            <dd>
                                <div class="prop-item">
                                    <%if(o.Type==0){%>
                                    <input type="text" name="prop.<%=o.Id%>" class="form-control" />
                                    <%}%>
                                    <%if(o.Type==1 || o.Type==2){%>
                                    <%var values=_.where(model.PropValues,{PropId:o.Id})%>
                                    <select name="prop.<%=o.Id%>" class="form-control" data-category="<%=o.CategoryId%>">
                                        <%if(o.Required==false){%>
                                        <option value="">请选择</option>
                                        <%}%>
                                        <% _.each(values,function(v){ %>
                                        <option value="<%=o.Id%>:<%=v.Id%>">
                                            <%=v.Name%>
                                        </option>
                                        <%});%>
                                    </select>

                                    <%}%>
                                    <% if(o.Type==3 ||o.Type==4){%>
                                    <%var values=_.where(model.PropValues,{PropId:o.Id})%>
                                    <ul class="list-inline">
                                        <% _.each(values,function(v){ %>
                                        <li>
                                            <label class="checkbox-inline">
                                                <input name="prop.<%=o.Id%>" type="checkbox" value="<%=o.Id%>:<%=v.Id%>" /><%=v.Name%>
                                            </label>
                                        </li>
                                        <%});%>
                                    </ul>
                                    <%}%>
                                </div>
                            </dd>
                            <%});%>
                        </dl>
                        <div>
                        </div>
                    </div>
                </div>
                <div class="col-md-9">
                    <div style="margin: 10px 20px 20px 0;">
                        <%if(keyProps.length>0){%>
                        <div class="form-group">
                            <p>商品属性</p>
                            <div class="prop-wrap">
                                <% _.each(keyProps,function(o){ %>
                                <div class="prop-container">
                                    <div class='prop-item'>
                                        <label><%=o.Name%> <%if(o.Required==true){%><span style="color: red;">*</span><%}%></label>
                                        <%if(o.Type==0){%>
                                        <input name="prop.<%=o.Id%>" type="text" class="form-control" />
                                        <%}%>
                                        <% if(o.Type==1 || o.Type==2){%>
                                        <%var values=_.where(model.PropValues,{PropId:o.Id})%>
                                        <select name="prop.<%=o.Id%>" data-category="<%=o.CategoryId%>" class="form-control">
                                            <% _.each(values,function(v){ %>
                                            <option value="<%=o.Id%>:<%=v.Id%>">
                                                <%=v.Name%>
                                            </option>
                                            <%});%>
                                        </select>
                                        <%}%>
                                    </div>
                                </div>
                                <%});%>
                            </div>
                        </div>
                        <%}%>
                        <div id="form-group-for-outerid" class="form-group">
                            <label class="control-label">商品编码</label>
                            <input name="prop.outerId" type="text" class="form-control" maxlength="20" />
                            <p class="help-block text-danger">请输入商品编码（20个字符以内）。</p>
                        </div>
                        <div id="form-group-for-name" class="form-group">
                            <label class="control-label">商品名称</label>
                            <input name="prop.name" type="text" class="form-control" onkeyup="ayatta.seller.item.NameOnKeyup(this);" onblur="ayatta.seller.item.NameOnBlur(this);" />
                            <p class="help-block text-danger">请输入商品名称（60字节以内,一个中文两字节）。<span id="item-name-len"></span></p>
                        </div>
                        <div id="form-group-for-subname" class="form-group">
                            <label class="control-label">副 名 称</label>
                            <input name="prop.subName" type="text" class="form-control" />
                            <p class="help-block text-danger">请输入商品副名称（为空或30字以内）。</p>
                        </div>

                        <%if(saleProps.length>0){%>
                        <%Sku.Keys=[];Sku.Names=[],Sku.PropIds=[];Sku.Skus=null;%>
                        <div class="form-group">
                            <label>商品规格</label>
                            <div class="controls">
                                <div class="prop-wrap">
                                    <%
                                    var colorProp=null;
                                    var colorPropValues=[];
                                    %>
                                    <% _.each(saleProps,function(o){ %>
                                    <%
                                    var key=[];
                                    Sku.Names.push(o.Name);
                                    Sku.PropIds.push(o.Id);
                                    %>
                                    <div class="prop-container">
                                        <label>
                                            <%=o.Name%>：
                                            <%if(o.IsColorProp==true){%><i class="icon-info-sign"></i><span class="text-danger">
                                                请尽量选择已有的颜色，如果自定义也请选择相近的颜色进行自定义！
                                            </span>
                                            <%}%>
                                        </label>
                                        <ul class="list-inline">
                                            <% if(o.Type==3 ||o.Type==4){%>
                                            <%var values=_.where(model.PropValues,{PropId:o.Id})%>

                                            <%if(o.IsColorProp==true){colorProp=o;colorPropValues=values;}%>
                                            <% _.each(values,function(v){ %>
                                            <%key.push(o.Id+':'+v.Id);%>
                                            <li>
                                                <label class="checkbox-inline">
                                                    <input name="prop.<%=o.Id%>" type="checkbox" value="<%=o.Id%>:<%=v.Id%>" data-sale="true" data-category="<%=o.CategoryId %>" /><%=v.Name%>
                                                </label>
                                            </li>
                                            <%});%>
                                            <%}%>
                                        </ul>
                                    </div>
                                    <%Sku.Keys.push(key);%>
                                    <%});%>
                                </div>
                                <%if(colorProp!=null){%>
                                <div class="sku-color" style="display:none;">
                                    <table class="table table-bordered">
                                        <thead>
                                            <tr>
                                                <th>
                                                    颜色分类
                                                </th>
                                                <th>
                                                    图片（必须上传该颜色对应图片，无图片可不填）
                                                </th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <%_.each(colorPropValues,function(o){ %>
                                            <tr id="pic-<%=o.PropId%>-<%=o.Id%>" style="display:none;">
                                                <td><%=o.Name %></td>
                                                <td>
                                                    <a class="btn btn-default btn-sm a-input-file" href="javascript:void(0);">
                                                        选择图片
                                                        <input type="file" name="image" class="input-file" onchange="imageUpload(this,0,'<%=o.PropId%>:<%=o.Id%>')" />
                                                    </a>
                                                    <input id="prop-image-<%=o.PropId%>-<%=o.Id%>" type="hidden" name="prop.img.<%=o.PropId%>:<%=o.Id%>" />
                                                </td>
                                            </tr>
                                            <%}); %>
                                        </tbody>
                                    </table>
                                </div>
                                <%} %>
                                <div class="sku-map">
                                    <div id="sku-table" style="display:none;">
                                    </div>
                                    <div id="msg-attention" class="msg-attention" style="display:none;">
                                        <i class="icon icon-attention"></i>
                                        <p class="text-danger">您需要选择所有的销售属性，才能组合成完整的规格信息。</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <%}%>
                        <div id="form-group-for-price" class="form-group">
                            <label class="control-label">商品价格</label>
                            <input name="prop.price" type="text" class="form-control" maxlength="9" onkeyup="ayatta.seller.item.PriceOnKeyup(this);" onblur="ayatta.seller.item.PriceOnBlur(this);" />
                            <p class="help-block text-danger">价格应在销售属性表中所填最高与最低价格范围区间内，以元为单位，精确到小数点后两位（取值范围：0-99999999）。</p>
                        </div>
                        <div id="form-group-for-quantity" class="form-group">
                            <label class="control-label">商品数量</label>
                            <input name="prop.quantity" type="text" class="form-control" maxlength="8" onkeyup="ayatta.seller.item.QuantityOnKeyup(this);" onblur="ayatta.seller.item.QuantityOnBlur(this);" />
                            <p class="help-block text-danger">请如实填写（取值范围：0-99999999）。</p>
                        </div>
                        <div class="form-group">
                            <label>商品图片</label>
                            <div class="prop-wrap prop-wrap-blue">
                                <div class="prop-container">
                                    <div class="row">
                                        <div class="col-md-12">
                                            <p class="text-muted">800px*800px以上的图片，可以在宝贝详情页提供图片放大功能。</p>
                                            <p class="text-muted">背景图是提供的范例，请尽量参照范例选图，发布后范例不会显示。</p>
                                            <div>
                                                <ul class="list-inline">
                                                    <li>
                                                        <p class="image-preview">
                                                            <img id="preview-1" src="http://img.taobaocdn.com/imgextra/T15iCxXoxDXXb1upjX_100x100.jpg" />
                                                        </p>
                                                        <p>
                                                            <a class="btn btn-default btn-sm a-input-file" href="javascript:void(0);">
                                                                选择图片
                                                                <input type="file" name="image" class="input-file" onchange="imageUpload(this,1,null)" />
                                                            </a>
                                                            <input id="prop-image-1" type="hidden" name="prop.img.1">
                                                        </p>
                                                    </li>
                                                    <li>
                                                        <p class="image-preview">
                                                            <img id="preview-2" src="http://img.taobaocdn.com/imgextra/T15iCxXoxDXXb1upjX_100x100.jpg" />
                                                        </p>
                                                        <p>
                                                            <a class="btn btn-default btn-sm a-input-file" href="javascript:void(0);">
                                                                选择图片
                                                                <input type="file" name="image" class="input-file" onchange="imageUpload(this,2,null)" />
                                                            </a>
                                                            <input id="prop-image-2" type="hidden" name="prop.img.2">
                                                        </p>
                                                    </li>
                                                    <li>
                                                        <p class="image-preview">
                                                            <img id="preview-3" src="http://img.taobaocdn.com/imgextra/T15iCxXoxDXXb1upjX_100x100.jpg" />
                                                        </p>
                                                        <p>
                                                            <a class="btn btn-default btn-sm a-input-file" href="javascript:void(0);">
                                                                选择图片
                                                                <input type="file" name="image" class="input-file" onchange="imageUpload(this,3,null)" />
                                                            </a>
                                                            <input id="prop-image-3" type="hidden" name="prop.img.3">
                                                        </p>
                                                    </li>
                                                    <li>
                                                        <p class="image-preview">
                                                            <img id="preview-4" src="http://img.taobaocdn.com/imgextra/T15iCxXoxDXXb1upjX_100x100.jpg" />
                                                        </p>
                                                        <p>
                                                            <a class="btn btn-default btn-sm a-input-file" href="javascript:void(0);">
                                                                选择图片
                                                                <input type="file" name="image" class="input-file" onchange="imageUpload(this,4,null)" />
                                                            </a>
                                                            <input id="prop-image-4" type="hidden" name="prop.img.4">
                                                        </p>
                                                    </li>
                                                    <li>
                                                        <p class="image-preview">
                                                            <img id="preview-5" src="http://img.taobaocdn.com/imgextra/T15iCxXoxDXXb1upjX_100x100.jpg" />
                                                        </p>
                                                        <p>
                                                            <a class="btn btn-default btn-sm a-input-file" href="javascript:void(0);">
                                                                选择图片
                                                                <input type="file" name="image" class="input-file" onchange="imageUpload(this,5,null)" />
                                                            </a>
                                                            <input id="prop-image-5" type="hidden" name="prop.img.5">
                                                        </p>
                                                    </li>
                                                </ul>
                                            </div>
                                            <p class="text-danger">
                                                图片至少上传1张，图片类型只能为gif,png,jpg,jpeg，且大小不超过1M。
                                            </p>
                                            <p class="text-muted">
                                                请不要在图片上添加除商品外的其他信息, 诸如水印、商标、优惠信息等。
                                            </p>
                                        </div>

                                    </div>
                                </div>
                            </div>

                        </div>
                        <div id="form-group-for-desc" class="form-group">
                            <label class="control-label">商品描述</label>
                            <textarea name="prop.desc" row="50" class="form-control"></textarea>
                            <p class="help-block">请输入商品描述（5至25000个字）。</p>
                        </div>

                        <div class="form-group">
                            <label>库存计数</label>
                            <div>
                                <label class="radio">
                                    <input type="radio" name="prop.subStock" value="0" checked="checked" />
                                    拍下减库存<span class="text-danger" style="margin-left:10px;">买家拍下商品即减少库存，存在<a target="blank" href="http://service.taobao.com/support/knowledge-5104445.htm?spm=0.0.0.122.83ee7e">恶拍</a>风险。秒杀、超低价等热销商品，如需避免超卖可选此方式</span>
                                </label>

                                <label class="radio">
                                    <input type="radio" name="prop.subStock" value="1" />
                                    付款减库存<span class="text-danger" style="margin-left:10px;">买家拍下并完成付款方减少库存，存在<a target="blank" href="http://service.taobao.com/support/knowledge-1110945.htm?spm=a220z.1000885.0.103.c88ca1">超卖</a>风险。如需减少恶拍、提高回款效率，可选此方式</span>
                                </label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>开始时间</label>
                            <div class="controls">
                                <p>
                                    <label class="radio">
                                        <input type="radio" name="prop.onlineTime" value="0" checked="checked" />
                                        立刻
                                    </label>
                                </p>
                                <p>
                                    <label class="radio">
                                        <input type="radio" name="prop.onlineTime" value="" />
                                        设定
                                    </label>
                                </p>
                                <p>
                                    <label class="radio">
                                        <input type="radio" name="prop.onlineTime" value="1" />
                                        放入仓库
                                    </label>
                                </p>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-3">
                                <input type="hidden" name="prop.hierarchyid" value="<%=model.HierarchyId%>" />
                                <button id="btn-submit" class="ui-btn ui-btn-alpha" type="submit" data-default-text="保 存"
                                        data-loading-text="数据提交中...">
                                    保 存
                                </button>
                            </div>
                            <div class="col-md-3">
                                <button type="reset" class="ui-btn ui-btn-beta">取 消</button>
                            </div>
                            <div class="col-md-3"><p id="result-message"></p></div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </script>
    <script type="text/javascript">
        document.domain = 'ayatta.com';

        function imageUploadCallback(result) {
            if (result.Status == true) {
                var data = result.Data;
                $('#prop-image-' + result.Extra).val(data);
                var src = "/temp/" + data;
                $('#preview-' + result.Extra).attr('src', src);
            } else {
                alert(result.Message);
            }
        }

        function imageUpload(obj, param, prop) {
            var form = document.getElementById('form-upload');
            if (param == 0) {
                var html = $.format('选择图片<input type="file" name="image" class="input-file" onchange="imageUpload(this,0,\'{0}\')" />', prop);
                $(obj).parent().html(html);
                $('#frame-upload').html($(obj));

                form.action = '/item/upload/0?prop=' + prop;
                $(form).submit();
            } else if (param > 0 && param < 6) {
                var html = $.format('选择图片<input type="file" name="image" class="input-file" onchange="imageUpload(this,{0},null)" />', param);
                $(obj).parent().html(html);
                $('#frame-upload').html($(obj));

                form.action = '/item/upload/' + param;
                $(form).submit();
            }
        }

        function checkForm(form) {
            var action = form.action;
            var param = $(form).serialize();
            $('#btn-submit').button('loading');
            $.postJSON(action, param, function (result) {
                if (result.Status) {
                    //$('#btn-submit').
                    $('#result-message').removeClass('text-danger').addClass('text-success').html('添加商品成功！');
                } else {
                    var target = result.Data;
                    var targets = ["outerId", "name", "subName", "price", "quantity", "desc"];
                    $.each(targets, function (i, n) {
                        $("#form-group-for-" + n).removeClass('has-error');
                    });
                    var formgroup = "#form-group-for-" + target;
                    if ($.inArray(target, targets) != -1) {
                        $(formgroup).addClass('has-error');
                        $("input[name='prop." + target + "']").focus();
                    } else {
                        $('#result-message').removeClass('text-success').addClass('text-danger').html(result.Message);
                    }
                    $('#btn-submit').button('default');
                }
            });
            return false;
        }

        function GetSkuTable(names, skus, Keys) {
            var html = new Array();
            var table = new Array();
            var header = new Array();
            var body = new Array();
            table.push('<table class="table table-bordered">');
            header.push('<thead><tr>');
            _.each(names, function (o) {
                header.push('<th>');
                header.push(o);
                header.push('</th>');
            });
            header.push('<th>价 格<span style="color:red;">*</span></th><th>数 量<span style="color:red;">*</span></th>');
            header.push('</tr></thead>');
            body.push('<tbody>');
            //console.log(skus);
            for (var i = 0; i < skus.length; i++) {
                body.push('<tr>');
                if (Keys.length > 1) {
                    for (var j = 0; j < Keys.length; j++) {
                        if (j < Keys.length - 1 && i % Keys[Keys.length - 1].length == 0 && Keys[Keys.length - 1].length > 0) {
                            var row = 1;
                            var last = 0;
                            for (var r = j + 1; r <= Keys.length - 1; r++) {
                                if (r == Keys.length - 1) {
                                    last = Keys[r].length;
                                } else {
                                    var len = Keys[r].length;
                                    if (len > 1) {
                                        row *= len;
                                    } else {
                                        row = 0;
                                        row += len;
                                    }
                                }
                            }
                            if (i % (row * last) == 0) {
                                if ((row * last) > 1) {
                                    body.push('<td rowspan="' + (row * last) + '">');
                                } else {
                                    body.push('<td>');
                                }
                                if (j == 0) {
                                    body.push(Sku.GetValue(Keys[j][(i / (row * last))]));
                                } else {
                                    body.push(Sku.GetValue(Keys[j][(i / (row * last)) % Keys[j].length]));
                                }
                                body.push('</td>');
                            }
                        } else if (j = Keys.length - 1) {
                            body.push('<td>');
                            body.push(Sku.GetValue(Keys[j][i % Keys[j].length]));
                            body.push('</td>');
                        }
                    }
                } else {
                    body.push('<td>');
                    body.push(Sku.GetValue(Keys[0][i]));
                    body.push('</td>');
                }
                body.push('<td>');
                var id = skus[i];
                var priceInput = '<input type="text" name="sku.price.' + id + '" maxlength="9" class="form-control input-small sku-price" onkeyup="ayatta.seller.item.PriceOnKeyup(this);" onblur="ayatta.seller.item.PriceOnBlur(this);" />';
                body.push(priceInput);
                body.push('</td>');
                body.push('<td>');
                var quantityInput = '<input type="text" name="sku.quantity.' + id + '" maxlength="6" class="form-control input-sm input-mini sku-quantity" onkeyup="ayatta.seller.item.QuantityOnKeyup(this);" onblur="ayatta.seller.item.QuantityOnBlur(this);"/>';
                body.push(quantityInput);
                body.push('</td>');
                body.push('</tr>');
            }
            body.push('</tbody>');

            table.push(header.join(""));
            table.push(body.join(""));
            html.push(table.join(""));
            html.push('</table>');
            return html.join("");
        }

        function concatAll(items) {
            var base = items[0];
            var left = items.slice(1);
            if (left.length) {
                return mulit(base, left);
            } else {
                return base;
            }

            function mulit(base, leftArr) {
                var multiplier = leftArr[0];

                var newBase = [];
                for (var i = 0, len = base.length; i < len; i++) {
                    var b = base[i];
                    for (var j = 0, len2 = multiplier.length; j < len2; j++) {
                        var m = multiplier[j];
                        newBase.push(b + ';' + m);
                    }
                }

                var left = leftArr.slice(1);
                if (left.length) {
                    return mulit(newBase, left);
                } else {
                    return newBase;
                }
            }
        }

        $(function () {
            window.Sku = {
                Keys: [],
                SaleProps: [],
                SalePropValues: [],
                Names: [],
                PropIds: [],
                GetValue: function (id) {
                    return _.findWhere(Sku.SalePropValues, { Id: id }).Value;
                },
                Skus: null,
                GetSkuKeys: function () {
                    var keys = Sku.Keys;
                    var len = keys.length;

                    if (len == 1) {
                        return keys[0];
                    }
                    if (len > 1) {
                        var first = keys[0];
                        var next = keys[1];
                        var array = [];
                        for (var j = 0; j < first.length; j++) {
                            for (var k = 0; k < next.length; k++) {
                                var t = first[j] + ';' + next[k];
                                array.push(t);
                            }
                        }
                        if (len == 2) {
                            return array;
                        } else {
                            keys = keys.splice(0, 2, array);

                            keys = Sku.GetSkuKeys(keys);
                        }
                    }
                    return keys;
                }
            };
            window.Categories = [];

            window.getChildren = function (obj, index, id, hierarchyid) {

                var prefix = "category-";
                var curId = prefix + index;
                var nextId = prefix + (index + 1);
                var model = { Id: nextId, Index: index + 1, HierarchyId: hierarchyid, Data: {} };
                var template = _.template($('#categories-template').html());
                var category = _.findWhere(Categories, { Id: id });
                if (category != null && category.Children != null) {
                    model.Data = category.Children;
                    $("#" + curId).nextAll().remove();
                    $("#category-container").append(template({ model: model }));
                    return;
                } else {
                    $.postJSON('/common/productcategory', { param: id }, function (result) {
                        var category = { Id: id, Children: result, Props: [], PropValues: [] };
                        Categories.push(category);
                        model.Data = result;
                        $("#" + curId).nextAll().remove();
                        $("#category-container").append(template({ model: model }));
                    });
                }
                $('select').select2();
            };

            window.publishItem = function (categoryId, hierarchyId) {
                $("#category-info").hide();
                var model = { CategoryId: categoryId, HierarchyId: hierarchyId, Props: [], PropValues: [] };
                var template = _.template($('#item-template').html());
                var category = _.findWhere(Categories, { Id: categoryId });
                if (category != null && category.Props != null && category.PropValues != null) {
                    model.Props = category.Props;
                    model.PropValues = category.PropValues;
                    $("#item-container").html(template({ model: model }));
                    $("select[name^='prop.']").bind("change", getBrandChild);
                    $("input[data-sale='true']").bind("click", dynamicMap);
                    $('select').select2();
                    return;
                } else {
                    $.postJSON('/common/productcategoryprop', { param: categoryId }, function (result) {
                        var props = result.Props;
                        var propValues = result.PropValues;
                        category = _.findWhere(Categories, { Id: categoryId });
                        if (category != null) {
                            category.Props = props;
                            category.PropValues = propValues;
                        } else {
                            category = { Id: categoryId, Children: null, Props: props, PropValues: propValues };
                            Categories.push(category);
                        }
                        model.Props = props;
                        model.PropValues = propValues;
                        $("#item-container").html(template({ model: model }));
                        $("select[name^='prop.']").bind("change", getBrandChild);
                        $("input[data-sale='true']").bind("click", dynamicMap);
                        $('select').select2();

                        tinymce.init({
                            selector: "textarea",
                            plugins: [
                                "advlist autolink lists link image charmap print preview anchor",
                                "searchreplace visualblocks code fullscreen",
                                "insertdatetime table contextmenu paste"
                            ],
                            //external_plugins: {
                            //    "moxiemanager": "/js/moxiemanager/plugin.min.js"
                            //},
                            toolbar: "styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
                        });

                    });
                }

            };

            window.dynamicMap = function () {
                //                if (Sku.Skus == null) {
                //                    Sku.Skus = {};
                //                    var skuKeys = concatAll(Sku.Keys); //Sku.GetSkuKeys();
                //                    _.each(skuKeys, function (o) {
                //                        Sku.Skus[o] = { Price: 0, Quantity: 0, Selected: false };
                //                    });
                //                }

                var obj = this;
                var val = $(obj).val();
                var pid = parseInt(val.split(':')[0]);
                var vid = parseInt(val.split(':')[1]);
                var saleProps = Sku.SaleProps;
                var prop = _.findWhere(saleProps, { Id: pid });
                if (prop.IsSaleProp == true && prop.IsColorProp == true) {
                    var picId = "#pic-" + val.replace(":", "-");
                    if (obj.checked == true) {
                        $(picId).show();
                    } else {
                        $(picId).hide();
                    }
                    var len = $("input[name='prop." + pid + "']:checked").length;
                    if (len > 0) {
                        $(".sku-color").show();
                    } else {
                        $(".sku-color").hide();
                    }
                }
                var propCount = 0;
                var temp = [];
                var keys = [];
                _.each(Sku.PropIds, function (o) {
                    var key = [];
                    var els = $("input[name='prop." + o + "']:checked");
                    _.each(els, function (o) {
                        var v = $(o).val();
                        key.push(v);
                        var propValue = _.findWhere(Sku.PropValues, { Id: vid });
                        var value = { Id: v, Value: propValue.Name };
                        if (!_.findWhere(Sku.SalePropValues, { Id: v })) {
                            Sku.SalePropValues.push(value);
                        }

                    });
                    if (key.length > 0) {
                        keys.push(key);
                    }
                    var len = $("input[name='prop." + o + "']:checked").length;
                    if (len > 0) {
                        propCount += 1;
                    }
                    temp[o] = len;

                });

                if (propCount < saleProps.length) {
                    $("#sku-table").hide();
                    $("#msg-attention").show();
                    $('#form-group-for-quantity').show();
                    $('#form-group-for-quantity .prop.quantity').val('');
                    return;
                } else {
                    $("#msg-attention").hide();
                    $("#sku-table").show();
                    $('#form-group-for-quantity').hide();
                }
                var row = 1;
                _.each(_.values(temp), function (o) {
                    row *= o;
                });
                Sku.Skus = concatAll(keys);
                //var model = { Names: Sku.Names, Keys: keys, Skus: Sku.Skus, Row: row };
                //var template = _.template($('#sku-template').html());

                //$("#sku-table").html(template(model));
                var html = GetSkuTable(Sku.Names, Sku.Skus, keys);
                $("#sku-table").html(html);
            };

            window.getBrandChild = function () {
                var obj = this;
                var val = $(obj).val();
                var pid = parseInt(val.split(':')[0]);
                var vid = parseInt(val.split(':')[1]);
                var extra = parseInt($(obj).attr("data-extra") || 0);
                var categoryId = parseInt($(obj).attr("data-category"));
                var props = _.findWhere(Categories, { Id: categoryId }).Props;
                if (_.where(props, { ParentPid: pid }).length > 0) {

                    $(obj).parent().nextAll().remove();
                    //var cls = extra == 1 ? "class='span11'" : "";
                    var prop = _.findWhere(props, { ParentPid: pid, ParentVid: vid });
                    if (prop != null) {
                        var data = _.where(props, { ParentPid: prop.Id }); //子属性
                        if (data.length > 0) {
                            var array = new Array();
                            array.push("<div class='prop-item'><label>" + prop.Name + "</label><select name='prop." + prop.Id + "' data-category='" + categoryId + "' class='form-control'>");
                            _.each(data, function (v) {
                                array.push("<option value='" + prop.Id + ":" + v.ParentVid + "'>" + v.Name + "</option>");
                            });
                            array.push("</select></div>");
                            var html = array.join("");
                            $(obj).parent().parent().append(html);
                        } else {
                            var propsValues = _.findWhere(Categories, { Id: categoryId }).PropValues;
                            var values = _.where(propsValues, { PropId: prop.Id });
                            var array = new Array();
                            array.push("<div class='prop-item'><label>" + prop.Name + "</label><select name='prop." + prop.Id + "' data-category='" + categoryId + "' class='form-control'>");
                            _.each(values, function (v) {
                                array.push("<option value='" + prop.Id + ":" + v.Id + "'>" + v.Name + "</option>");
                            });
                            array.push("</select></div>");
                            var html = array.join("");
                            $(obj).parent().parent().append(html);
                        }
                    }
                    $('select').select2();
                    $("select[name^='prop.']").bind("change", getBrandChild);
                }
            };

        });



    </script>
}
